package blog.Interceptor;

import blog.service.thread.UserThreadLocal;
import blog.dao.pojo.SysUser;
import blog.utils.CheckToken;
import blog.vo.ErrorCode;
import blog.vo.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private CheckToken checker;

    // 访问相应资源没有登陆就会被拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (!(handler instanceof HandlerMethod)){
            return true;
        }

        String token = request.getHeader("Authorization");

        SysUser sysUser = checker.checkToken(token); // 检验token合法性，用户登录是否过期

        if (sysUser==null){
            Result failResult = Result.fail(ErrorCode.NO_LOGIN.getCode(), ErrorCode.NO_LOGIN.getMsg());

            response.setContentType("application/json;charset=utf-8");
            response.getWriter().println(new ObjectMapper().writeValueAsString(failResult));

            return false;
        }

        UserThreadLocal.put(sysUser);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
